package com.devcon5.StudentPlanner;

import java.text.DecimalFormat;
import java.util.ArrayList;

import database.CourseDAO;
import database.GradeDAO;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;
import baseclasses.Course;
import baseclasses.Grade;


public class ViewGrades extends Activity {
	
		//Widget variables
		private Context context = this;
		private GradeAdapter adapter;
		private ExpandableListView elv;
		private TextView title, gpaText;
		private ArrayList<Course> courses;
		private ArrayList<ArrayList<Grade>> grades;
		private int gradecount;
		
		private DecimalFormat df = new DecimalFormat("#.###");
		
		@Override
		public void onCreate(Bundle savedInstanceState){
			super.onCreate(savedInstanceState);
	        setContentView(R.layout.viewgrades);
	        
	        //Assign widget variables to UI
	        
	        title = (TextView) findViewById(R.id.viewgrades_title);
	        gpaText = (TextView)findViewById(R.id.viewgrades_gpatextview);
			elv = (ExpandableListView)findViewById(R.id.viewgrades_expandablelistview);
			
			adapter = new GradeAdapter();
			elv.setAdapter(new GradeAdapter());

			gradecount = GradeDAO.gradesCount(context);
			title.setText("Displaying "+courses.size()+" course(s) and " +
					gradecount+" grade(s)");
			gpaText.setText("GPA: "+ df.format(calculateGPA()) );
			
			elv.setOnChildClickListener(new OnChildClickListener(){ //when items in expandable list view clicked

				public boolean onChildClick(ExpandableListView parent, View v,
						int groupPosition, int childPosition, long id) {
					
					final Grade grade = adapter.getChild(groupPosition, childPosition);	//get the grade
					
					AlertDialog.Builder builder = new AlertDialog.Builder(context);	//and display the edit/delete dialog for that grade
					builder.setTitle(grade.getName());
					builder.setIcon(R.drawable.grades);
					builder.setItems(new CharSequence[] {"Edit", "Delete"}, new OnClickListener(){
						
						public void onClick(DialogInterface dialog, int which){
							
							final int EDIT = 0;
							final int DELETE = 1;

							switch(which){

							case EDIT:
								Intent editIntent = new Intent(context, EditGrade.class); 		//pass grade in from view grade view to editgrade class
								editIntent.putExtra( Grade.GRADE_ID, grade.getId());
								startActivity(editIntent);
								return;

							case DELETE:	//confirm that they want to delete the grade
								AlertDialog.Builder builder = new AlertDialog.Builder(context);
								builder.setTitle("Delete?");
								builder.setIcon(android.R.drawable.ic_delete);
								builder.setMessage("Are you sure you want to delete "+grade.getName()+"?");
								builder.setPositiveButton("Delete", new OnClickListener() {

									
									public void onClick(DialogInterface dialog, int which) {
								
										GradeDAO.deleteGrade(context, grade);
										refreshList();
									}
								});
								builder.setNegativeButton("Cancel", null);
								AlertDialog alert = builder.create();
								alert.show();
								return;
						}
					}
					
					});
					AlertDialog alert = builder.create();
					alert.show();
					return false;
				}
				
			});
	        
		}
        
		@Override
		public void onResume(){
			super.onResume();
			refreshList();
    }
		
	//Customizable ExpandableListAdapter
		public class GradeAdapter extends BaseExpandableListAdapter {
			
			public GradeAdapter(){
				/*
				 * First, populate the courses array list with courses
				 * Then, populate grades array list with array lists of grades from courses
				 * all of this is done by ID, grouping the course together and the grades under a course
				 */
				courses = CourseDAO.getCourses(context);
				grades = new ArrayList<ArrayList<Grade>>();
				for(int i = 0; i < courses.size(); i++){
					grades.add(GradeDAO.getGradesByCourseId(context, courses.get(i).getId()));
				}
				
			}
			
			public Grade getChild(int groupPosition, int childPosition) {
				return grades.get(groupPosition).get(childPosition);
			}

			public long getChildId(int groupPosition, int childPosition) {
				return childPosition;
			}

			public int getChildrenCount(int groupPosition) {
				return grades.get(groupPosition).size();
			}

			public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

				View v = convertView;

				if (v == null) {
					//Constructor method sets the activity which calls the adapter, and
					//this inflates a new expandable list item view in that activity
					LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
					v = vi.inflate(android.R.layout.simple_expandable_list_item_2, null);
				}
				
				
				Grade grade = getChild(groupPosition, childPosition);
				if (grade != null) {
					TextView text1 = (TextView) v.findViewById(android.R.id.text1);
					TextView text2 = (TextView) v.findViewById(android.R.id.text2);
					text1.setSingleLine();
					text2.setSingleLine();
					text1.setText(grade.getName());
					text2.setText(grade.getGradeString(context));
				}
				return v;
			}

			public Course getGroup(int groupPosition) {
				return courses.get(groupPosition);
			}

			public int getGroupCount() {
				return courses.size();
			}

			public long getGroupId(int groupPosition) {
				return groupPosition;
			}

			public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

				View v = convertView;
				if (v == null) {
					//Constructor method sets the activity which calls the adapter, and
					//this inflates a new expandable list item view in that activity
					LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
					v = vi.inflate(android.R.layout.simple_expandable_list_item_2, null);
				}
				 
				Course course = getGroup(groupPosition);
				if (course != null) {
					TextView text1 = (TextView) v.findViewById(android.R.id.text1);
					text1.setSingleLine();
					TextView text2 = (TextView) v.findViewById(android.R.id.text2);
					text2.setSingleLine();
					text1.setText(course.getName());
					text2.setText(course.getGradeString(context));
				}
				return v;
			}

			public boolean isChildSelectable(int groupPosition, int childPosition) {
				return true;
			}

			public boolean hasStableIds() {
				return true;
			}
		}
		
		//Refresh the expandable list view by creating a new GradeAdapter and loading data into it.
		public void refreshList(){
			adapter = new GradeAdapter();
			elv.setAdapter(new GradeAdapter());
			
			gradecount = GradeDAO.gradesCount(context);
			title.setText("Displaying " + courses.size() + " course(s) and " +
					gradecount + " grade(s)");
			gpaText.setText("GPA: " + df.format(calculateGPA()));
		}
		
		//Returns whether courses exist or not
		public boolean coursesExist(){
			if (CourseDAO.getCourses(context).size() > 0){
				return true;
			}
			return false;
		}
		
		public double calculateGPA(){
			
			int creditHours = 0;
			double total = 0;
			
			Course c;
			for(int i=0; i < courses.size(); i++){
				c = courses.get(i);
				if (c.getWeight(context) != -1){
					creditHours += c.getCredits();
					total += (c.getWeight(context) * c.getCredits());
				}
			}
			
			return total/creditHours;
		}
		
		//---------------------------------------------------------
		//
		//						MENU METHODS
		//
		//---------------------------------------------------------
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.viewgradesmenu, menu);
			return true;
		}

		//Item selection handler
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
			case R.id.viewgradesmenu_addgrade:
				//Check if courses exist. If they do, start the AddGrade class
				//If they don't, alert the user and provide a way to add a course
				if(coursesExist()){
					startActivity(new Intent(context, AddGrade.class));
				}
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle("No courses available");
					builder.setMessage("You must add a course before adding an grade");
					builder.setPositiveButton("Add Course", new OnClickListener(){
						
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(context, AddCourse.class));
						}
					});
					builder.setNegativeButton("Cancel", null);
					AlertDialog alert = builder.create();
					alert.show();
				}
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
		
}
